package com.lc.zpyh.ui.activity.mine;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hjq.http.EasyConfig;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.umeng.Platform;
import com.lc.umeng.UmengClient;
import com.lc.umeng.UmengLogin;
import com.lc.widget.view.CountdownView;
import com.lc.widget.view.RegexEditText;
import com.lc.widget.view.ScaleImageView;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.bean.CodeBean;
import com.lc.zpyh.bean.PasswordBean;
import com.lc.zpyh.http.request.AndroidQQUserLoginApi;
import com.lc.zpyh.http.request.AndroidWeChatLoginApi;
import com.lc.zpyh.http.request.BindPushRidApi;
import com.lc.zpyh.http.request.IsqqOpenIdApi;
import com.lc.zpyh.http.request.PublicMsgBean;
import com.lc.zpyh.http.request.SaveQQUserApi;
import com.lc.zpyh.http.request.SecondTestApi;
import com.lc.zpyh.http.request.SendSmsApi;
import com.lc.zpyh.http.request.VerificationCodeApi;
import com.lc.zpyh.http.request.VerificationPassWordApi;
import com.lc.zpyh.http.request.WXLoginBean;
import com.lc.zpyh.http.response.IsqqOpenIdBean;
import com.lc.zpyh.http.response.QQLoginBean;
import com.lc.zpyh.http.response.SaveQQUserBean;
import com.lc.zpyh.http.response.VerificationCodeBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.BindMobilePhoneNumberActivity;
import com.lc.zpyh.util.CustomizeUtils;
import com.lc.zpyh.util.SPUtil;
import com.mob.MobSDK;
import com.mob.pushsdk.MobPush;
import com.mob.secverify.CustomUIRegister;
import com.mob.secverify.CustomViewClickListener;
import com.mob.secverify.GetTokenCallback;
import com.mob.secverify.OAuthPageEventCallback;
import com.mob.secverify.PageCallback;
import com.mob.secverify.PreVerifyCallback;
import com.mob.secverify.SecVerify;
import com.mob.secverify.UiLocationHelper;
import com.mob.secverify.common.exception.VerifyException;
import com.mob.secverify.datatype.VerifyResult;
import com.mob.secverify.ui.component.CommonProgressDialog;
import com.mob.tools.utils.ResHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class LoginCodeActivity extends AppActivity implements UmengLogin.OnLoginListener {
    @BindView(R.id.et_login_phone)
    EditText etLoginPhone;
    @BindView(R.id.et_login_code)
    RegexEditText etLoginCode;
    @BindView(R.id.cv_phone_reset_countdown)
    CountdownView cvPhoneResetCountdown;
    @BindView(R.id.btn_login_commit)
    Button mCommitView;
    @BindView(R.id.ll_login_body)
    LinearLayout llLoginBody;
    @BindView(R.id.ll_login_other)
    LinearLayout llLoginOther;
    @BindView(R.id.iv_login_wechat)
    ScaleImageView ivLoginWechat;
    @BindView(R.id.iv_login_qq)
    ScaleImageView ivLoginQq;
    @BindView(R.id.check_tongyi)
    CheckBox checkTongyi;
    @BindView(R.id.tv_xieyi)
    TextView tvXieyi;
    @BindView(R.id.yinsi)
    TextView yinsi;
    Platform platform;
    @BindView(R.id.view_code)
    View viewCode;
    @BindView(R.id.view_password)
    View viewPassword;
    @BindView(R.id.ll_code)
    RelativeLayout llCode;

    @BindView(R.id.et_login_password)
    RegexEditText etLoginPassword;
    @BindView(R.id.ll_password)
    LinearLayout llPassword;
    private boolean isPreVerifyDone;
    private boolean isVerifySupport = false;
    private long starttime;
    private static final String TAG = "LoginCodeActivity";
    private String login="1";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_logincode;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        isPreVerifyDone = SPUtil.get(this, "isPreVerifyDone", false);
        Log.e(TAG, "isPreVerifyDone: " + isPreVerifyDone);
        // 判断用户当前有没有安装 QQ
        if (!UmengClient.isAppInstalled(this, Platform.QQ)) {
            ivLoginQq.setVisibility(View.GONE);
        }

        // 判断用户当前有没有安装微信
        if (!UmengClient.isAppInstalled(this, Platform.WECHAT)) {
            ivLoginWechat.setVisibility(View.GONE);
        }

        // 如果这两个都没有安装就隐藏提示
        if (ivLoginQq.getVisibility() == View.GONE && ivLoginWechat.getVisibility() == View.GONE) {
            llLoginOther.setVisibility(View.GONE);
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        // 自动填充手机号和密码
        isVerifySupport = SecVerify.isVerifySupport();

        if (isVerifySupport) {

            if (!isPreVerifyDone) {
                Log.e(TAG, "preVerify: ");
                preVerify();
            }

        } else {
            Toast.makeText(this, "当前环境不支持", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick({R.id.image_back, R.id.cv_phone_reset_countdown, R.id.btn_login_commit, R.id.iv_login_wechat, R.id.iv_login_qq, R.id.tv_xieyi, R.id.yinsi, R.id.iv_login_miaoyan, R.id.rl_code, R.id.rl_password,R.id.tv_forget})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_code:
                viewCode.setVisibility(View.VISIBLE);
                viewPassword.setVisibility(View.INVISIBLE);
                llCode.setVisibility(View.VISIBLE);
                llPassword.setVisibility(View.GONE);
                login = "1";
                break;
            case R.id.rl_password:
                viewCode.setVisibility(View.INVISIBLE);
                viewPassword.setVisibility(View.VISIBLE);
                llCode.setVisibility(View.GONE);
                llPassword.setVisibility(View.VISIBLE);
                login = "2";
                break;
            case R.id.tv_forget:
                startActivity(ForgetPassWordActivity.class);
                break;
            case R.id.image_back:
                finish();
                break;
            case R.id.iv_login_miaoyan:
                if (!checkTongyi.isChecked()) {
                    toast("请同意《用户协议》及《隐私条款》");
                    return;
                }
//              /                暂时跳到邀请码
//                // 添加自定义控件
                // 自定义UI
                Log.e(TAG, "onClick: " + isPreVerifyDone);
                if (!isPreVerifyDone) {
                    Toast.makeText(LoginCodeActivity.this, "请等待预登录完成", Toast.LENGTH_SHORT).show();
                    return;
                }
                addCustomView();
                customizeUi();
//				SecVerify.setAdapterFullName("com.mob.secverify.demo.ui.component.MyAdapter");
                SecVerify.autoFinishOAuthPage(false);
                isVerifySupport = SecVerify.isVerifySupport();
                if (isVerifySupport) {
                    verify();
                } else {
                    Toast.makeText(this, "当前环境不支持", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.cv_phone_reset_countdown:
                if (etLoginPhone.getText().toString().length() != 11) {
                    etLoginPhone.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.shake_anim));
                    toast(R.string.common_phone_input_error);

                    return;
                }

                EasyHttp.post(this)
                        .api(new SendSmsApi()
                                .setPhone(etLoginPhone.getText().toString())).request(new HttpCallback<PublicMsgBean>(this) {

                    @Override
                    public void onStart(Call call) {
                        cvPhoneResetCountdown.start();
                    }

                    @Override
                    public void onEnd(Call call) {

                    }

                    @Override
                    public void onSucceed(PublicMsgBean data) {
                        toast(data.getList());
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);

                    }
                });

                break;
            case R.id.btn_login_commit:
                 if (login.equals("1")){
                     codeLogin();
                 }else {
                    passwordLogin();
                 }


                break;
            case R.id.iv_login_wechat:
                if (!checkTongyi.isChecked()) {
                    toast("请同意《用户协议》及《隐私条款》");
                    return;
                }
                platform = Platform.WECHAT;
//                toast("也别忘了改微信 " + WXEntryActivity.class.getSimpleName() + " 类所在的包名哦");
                UmengClient.login(this, platform, this);
                break;
            case R.id.iv_login_qq:
                if (!checkTongyi.isChecked()) {
                    toast("请同意《用户协议》及《隐私条款》");
                    return;
                }
                platform = Platform.QQ;
                UmengClient.login(this, platform, this);
                break;
            case R.id.tv_xieyi:
                startActivity(new Intent(this, XieYiActivity.class).putExtra("title","用户协议"));
//                UIHelper.startActivity(this,XieYiActivity.class);

                break;
            case R.id.yinsi:
                startActivity(new Intent(this, XieYiActivity.class).putExtra("title","隐私条款"));

                break;
        }
    }

    private void passwordLogin() {
        if (etLoginPhone.getText().toString().length() != 11) {

            toast(R.string.common_phone_input_error);
            return;
        }
        if (etLoginPassword.getText().toString().isEmpty()) {

            toast(R.string.common_password_input_error);
            return;
        }
        if (!checkTongyi.isChecked()) {
            toast("请同意《用户协议》及《隐私条款》");
            return;
        }
        // 隐藏软键盘
        hideKeyboard(getCurrentFocus());
        EasyHttp.post(this)
                .api(new VerificationPassWordApi()
                        .setUserPhone(etLoginPhone.getText().toString()).setPassWord(etLoginPassword.getText().toString())).request(new HttpCallback<PasswordBean>(this) {


            @Override
            public void onSucceed(PasswordBean data) {
                if (data.getCode() == 0) {
                    toast("登录成功");

                    SPUtil.put(LoginCodeActivity.this, IntentKey.PHONE, data.getList().getUserInfo().getUserPhone());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.ACCOUNT, data.getList().getUserInfo().getUserAccount());

                    SPUtil.put(LoginCodeActivity.this, IntentKey.INVITECODE, data.getList().getUserInfo().getInviteCode());

                    SPUtil.put(LoginCodeActivity.this, IntentKey.USERID, data.getList().getUserInfo().getUserId() + "");


                    SPUtil.put(LoginCodeActivity.this, IntentKey.USERID, String.valueOf(data.getList().getUserInfo().getUserId()));
                    bindPushRid(data.getList().getUserInfo().getUserId() + "", "");
                    if (data.getList().isFirst()) {
                        startActivity(new Intent(LoginCodeActivity.this, InvitationCodeActivity.class).putExtra(IntentKey.USERID, data.getList().getUserInfo().getUserId() + ""));
                    }


                } else {
                    toast("验证失败");
                }

            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void codeLogin() {
        if (etLoginPhone.getText().toString().length() != 11) {

            toast(R.string.common_phone_input_error);
            return;
        }
        if (etLoginCode.getText().toString().isEmpty()) {

            toast(R.string.common_code_input_hint);
            return;
        }
        if (!checkTongyi.isChecked()) {
            toast("请同意《用户协议》及《隐私条款》");
            return;
        }
        // 隐藏软键盘
        hideKeyboard(getCurrentFocus());
        EasyHttp.post(this)
                .api(new VerificationCodeApi()
                        .setPhone(etLoginPhone.getText().toString()).setCode(etLoginCode.getText().toString())).request(new HttpCallback<VerificationCodeBean>(this) {


            @Override
            public void onSucceed(VerificationCodeBean data) {
                if (data.getCode() == 0) {
                    toast("登录成功");
                    EasyConfig.getInstance()
                            .addParam(IntentKey.TOKEN, data.getList().getToken());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.PHONE, data.getList().getUseInfo().getUserPhone());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.ACCOUNT, data.getList().getUseInfo().getUserAccount());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.TOKEN, data.getList().getToken());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.INVITECODE, data.getList().getUseInfo().getInviteCode());

                    SPUtil.put(LoginCodeActivity.this, IntentKey.USERID, data.getList().getUseInfo().getUserId() + "");


                    SPUtil.put(LoginCodeActivity.this, IntentKey.USERID, String.valueOf(data.getList().getUseInfo().getUserId()));
                    bindPushRid(data.getList().getUseInfo().getUserId() + "", "");
                    if (data.getList().isFirst()) {
                        startActivity(new Intent(LoginCodeActivity.this, InvitationCodeActivity.class).putExtra(IntentKey.USERID, data.getList().getUseInfo().getUserId() + ""));
                    }


                } else {
                    toast("验证失败");
                }

            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void bindPushRid(String userid, String miaoyan) {
        MobPush.deleteAlias();
        UUID own = UUID.randomUUID();
        String uuid = own.toString();
        MobPush.setAlias(uuid);

        EasyHttp.post(this)
                .api(new BindPushRidApi()
                        .setUserId(userid)
                        .setRid(uuid)
                ).request(new HttpCallback<VerificationCodeBean>(this) {


            @Override
            public void onSucceed(VerificationCodeBean data) {
                if (miaoyan.equals("miaoyan")) {
                    SecVerify.finishOAuthPage();
                    CommonProgressDialog.dismissProgressDialog();
                }

                finish();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 友盟登录回调
        UmengClient.onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void onSucceed(Platform platform, UmengLogin.LoginData data) {
        if (isFinishing() || isDestroyed()) {
            // Glide：You cannot start a load for a destroyed activity
            return;
        }
        Log.e(TAG, "onSucceed: " + data.getId());
        // 判断第三方登录的平台
        switch (platform) {
            case QQ:
                IsqqOpenId(data.getName(), data.getSex(), data.getId());

                break;
            case WECHAT:
                AndroidWeChatLogin(data.getToken(), data.getId());
                break;
            default:
                break;
        }


    }

    private void IsqqOpenId(String name, String sex, String id) {

        EasyHttp.post(this)
                .api(new IsqqOpenIdApi()
                        .setQQOpenId(id)).request(new HttpCallback<IsqqOpenIdBean>(this) {


            @Override
            public void onSucceed(IsqqOpenIdBean data) {


                if (data.getCode() == 0) {
                    if (data.isList()) {
                        qqUserLogin(name, sex, id);
                    } else {
                        saveQQUser(name, sex, id);
                    }
                }


//


            }

            @Override
            public void onFail(Exception e) {
//                super.onFail(e);

            }
        });

    }

    private void qqUserLogin(String name, String sex, String id) {
        EasyHttp.post(this)
                .api(new AndroidQQUserLoginApi()
                        .setQQOpenId(id)).request(new HttpCallback<QQLoginBean>(this) {


            @Override
            public void onSucceed(QQLoginBean data) {

//                finish();

                if (data.getCode() == 101) {
                    saveQQUser(name, sex, id);
                    Log.e("@@@", "onSucceed: " + data.getList());
                } else if (data.getCode() == 0) {
                    SPUtil.put(LoginCodeActivity.this, IntentKey.PHONE, data.getList().getUserPhone());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.ACCOUNT, data.getList().getUserAccount());
//                SPUtil.put(LoginCodeActivity.this, IntentKey.TOKEN, data.getList().getUserInfo());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.INVITECODE, data.getList().getInviteCode());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.USERID, data.getList().getUserId() + "");
                    SPUtil.put(LoginCodeActivity.this, IntentKey.PHONE, data.getList().getUserPhone());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.USERQQPHONE, data.getList().getUserPhone());

                    if (data.getList().getUserPhone() == null || data.getList().getUserPhone().equals("") || data.getList().getUserPhone().isEmpty()) {
                        startActivity(new Intent(LoginCodeActivity.this, BindMobilePhoneNumberActivity.class).putExtra("type", "qq"));
                    }
                    bindPushRid(data.getList().getUserId() + "", "");
                } else {
                    toast(data.getMsg());
                }

//


            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void saveQQUser(String name, String sex, String id) {
        if (sex.equals("男")) {
            sex = "1";
        } else {
            sex = "2";
        }


        EasyHttp.post(this)
                .api(new SaveQQUserApi()
                        .setQqOpenId(id).setSchoolId("").setUserAccount("").setUserGender(sex).setUserName(name).setUserPhone("")).request(new HttpCallback<SaveQQUserBean>(this) {


            @Override
            public void onSucceed(SaveQQUserBean data) {

//                finish();


                SPUtil.put(LoginCodeActivity.this, IntentKey.PHONE, data.getList().getUserPhone());
                SPUtil.put(LoginCodeActivity.this, IntentKey.ACCOUNT, data.getList().getUserAccount());
//                SPUtil.put(LoginCodeActivity.this, IntentKey.TOKEN, data.getList().getUserInfo());
                SPUtil.put(LoginCodeActivity.this, IntentKey.INVITECODE, data.getList().getInviteCode());


                SPUtil.put(LoginCodeActivity.this, IntentKey.SEX, data.getList().getUserGender() + "");
                SPUtil.put(LoginCodeActivity.this, IntentKey.NICKNAME, data.getList().getUserName());
                SPUtil.put(LoginCodeActivity.this, IntentKey.HEADIMGURL, data.getList().getUserName());
                SPUtil.put(LoginCodeActivity.this, IntentKey.VXOPENID, data.getList().getVxOpenId());
                SPUtil.put(LoginCodeActivity.this, IntentKey.PHONE, data.getList().getUserPhone());
                SPUtil.put(LoginCodeActivity.this, IntentKey.USERID, data.getList().getUserId() + "");
                SPUtil.put(LoginCodeActivity.this, IntentKey.USERQQPHONE, data.getList().getUserPhone());

                if (data.getList().getUserPhone() == null || data.getList().getUserPhone().isEmpty()) {

                    startActivity(new Intent(LoginCodeActivity.this, BindMobilePhoneNumberActivity.class).putExtra("type", "qq"));
                }
                bindPushRid(data.getList().getUserId() + "", "");


            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void AndroidWeChatLogin(String token, String id) {
        EasyHttp.post(this)
                .api(new AndroidWeChatLoginApi()
                        .setAccess_token(token).setOpenid(id).setUserId("")).request(new HttpCallback<WXLoginBean>(this) {


            @Override
            public void onSucceed(WXLoginBean data) {
//                finish();
                if (data.getCode()==1000){
                    toast("授权失败");
                    return;
                }
                if (data.getCode()==0) {
                    if (data.getList().getUserInfo() != null) {
                        SPUtil.put(LoginCodeActivity.this, IntentKey.OPENID, id);
                        SPUtil.put(LoginCodeActivity.this, IntentKey.PHONE, data.getList().getUserInfo().getUserPhone());
                        SPUtil.put(LoginCodeActivity.this, IntentKey.ACCOUNT, data.getList().getUserInfo().getUserAccount());
//                SPUtil.put(LoginCodeActivity.this, IntentKey.TOKEN, data.getList().getUserInfo());
                        SPUtil.put(LoginCodeActivity.this, IntentKey.INVITECODE, data.getList().getUserInfo().getInviteCode());
                        SPUtil.put(LoginCodeActivity.this, IntentKey.USERID, data.getList().getUserInfo().getUserId() + "");


                        SPUtil.put(LoginCodeActivity.this, IntentKey.INVITECODE, data.getList().getUserInfo().getInviteCode());
                        SPUtil.put(LoginCodeActivity.this, IntentKey.INVITECODE, data.getList().getUserInfo().getInviteCode());
                        bindPushRid(data.getList().getUserInfo().getUserId() + "", "");
                    }
                    if (data.getList().getWxInfo() != null) {
                        SPUtil.put(LoginCodeActivity.this, IntentKey.NICKNAME, data.getList().getWxInfo().getNickname());
                        SPUtil.put(LoginCodeActivity.this, IntentKey.VXOPENID, data.getList().getWxInfo().getOpenid());
                        SPUtil.put(LoginCodeActivity.this, IntentKey.SEX, data.getList().getWxInfo().getSex() + "");
                        SPUtil.put(LoginCodeActivity.this, IntentKey.HEADIMGURL, data.getList().getWxInfo().getHeadimgurl());
                        finish();

                    }
                    if (data.getList().isNeedToBindMobilePhoneNumber()) {
                        SPUtil.put(LoginCodeActivity.this, IntentKey.NEEDTOBINDMOBILEPHONENUMBER, "0");
                        startActivity(new Intent(LoginCodeActivity.this, BindMobilePhoneNumberActivity.class).putExtra("type", "wx"));
                        finish();
                    } else {
                        SPUtil.put(LoginCodeActivity.this, IntentKey.NEEDTOBINDMOBILEPHONENUMBER, "1");

                        finish();

                    }
                }

            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    /**
     * 授权失败的回调
     *
     * @param platform 平台名称
     * @param t        错误原因
     */
    @Override
    public void onError(Platform platform, Throwable t) {
        toast("第三方登录出错：" + t.getMessage());
    }

    /**
     * 授权取消的回调
     *
     * @param platform 平台名称
     */
    @Override
    public void onCancel(Platform platform) {
        toast("取消第三方登录");
    }

    /**
     * 免密登录
     */
    private void verify() {
        CommonProgressDialog.showProgressDialog(this);
        //需要在verify之前设置
        SecVerify.OtherOAuthPageCallBack(new OAuthPageEventCallback() {
            @Override
            public void initCallback(OAuthPageEventResultCallback cb) {
                cb.pageOpenCallback(new PageOpenedCallback() {
                    @Override
                    public void handle() {
                        Log.i(TAG, System.currentTimeMillis() + " pageOpened");
                        Log.e(TAG, (System.currentTimeMillis() - starttime) + "ms is the time pageOpen take ");
                    }
                });
                cb.loginBtnClickedCallback(new LoginBtnClickedCallback() {
                    @Override
                    public void handle() {
                        Log.i(TAG, System.currentTimeMillis() + " loginBtnClicked");
                    }
                });
                cb.agreementPageClosedCallback(new AgreementPageClosedCallback() {
                    @Override
                    public void handle() {
                        Log.i(TAG, System.currentTimeMillis() + " agreementPageClosed");
                    }
                });
                cb.agreementPageOpenedCallback(new AgreementClickedCallback() {
                    @Override
                    public void handle() {
                        Log.i(TAG, System.currentTimeMillis() + " agreementPageOpened");
                    }
                });
                cb.cusAgreement1ClickedCallback(new CusAgreement1ClickedCallback() {
                    @Override
                    public void handle() {
                        Log.i(TAG, System.currentTimeMillis() + " cusAgreement1ClickedCallback");
                    }
                });
                cb.cusAgreement2ClickedCallback(new CusAgreement2ClickedCallback() {
                    @Override
                    public void handle() {
                        Log.i(TAG, System.currentTimeMillis() + " cusAgreement2ClickedCallback");
                    }
                });
                cb.checkboxStatusChangedCallback(new CheckboxStatusChangedCallback() {
                    @Override
                    public void handle(boolean b) {
                        Log.i(TAG, System.currentTimeMillis() + " current status is " + b);
                    }
                });
                cb.pageCloseCallback(new PageClosedCallback() {
                    @Override
                    public void handle() {
                        Log.i(TAG, System.currentTimeMillis() + " pageClosed");
                        HashMap<String, List<Integer>> map = UiLocationHelper.getInstance().getViewLocations();
                        if (map == null) {
                            return;
                        }
                        for (String key : map.keySet()) {
                            List<Integer> locats = map.get(key);
                            if (locats != null && locats.size() > 0) {
                                for (int i : locats) {
                                    Log.i(TAG, i + " xywh");
                                }
                            }
                        }
                    }
                });
            }
        });
        starttime = System.currentTimeMillis();
        SecVerify.verify(new PageCallback() {
            @Override
            public void pageCallback(int code, String desc) {
                Log.e(TAG, code + " " + desc);
                if (code != 6119140) {

                    isVerifySupport = SecVerify.isVerifySupport();

                    if (isVerifySupport) {


                        Log.e(TAG, "preVerify: ");
                        preVerify();


                    } else {
                        Toast.makeText(LoginCodeActivity.this, "当前环境不支持", Toast.LENGTH_SHORT).show();
                    }
                    CommonProgressDialog.dismissProgressDialog();

//                    if (devMode) {
//                        Toast.makeText(LoginCodeActivity.this, code + " " + desc, Toast.LENGTH_SHORT).show();
//                    }

                }
            }
        }, new GetTokenCallback() {
            @Override
            public void onComplete(VerifyResult data) {
                Log.d(TAG, "Login success. data: " + data.toJSONString());

                Gson gson = new Gson();
                CodeBean codeBean = gson.fromJson(data.toJSONString(), CodeBean.class);
                Log.d(TAG, "Login success. data: " + codeBean.getOpToken());
                logincode(codeBean.getOpToken(), codeBean.getOperator(), codeBean.getToken());


            }

            @Override
            public void onFailure(VerifyException e) {
//                isPreVerifyDone = true;
//                // Nothing to do
//                Throwable t = e.getCause();
//                String errDetail = null;
//                if (t != null){
//                    errDetail = t.getMessage();
//                }
//
////                if (devMode) {
//                    // 登录失败
//                    Log.e(TAG, "preVerify failed", e);
//                    // 错误码
//                    int errCode = e.getCode();
//                    // 错误信息
//                    String errMsg = e.getMessage();
//                    // 更详细的网络错误信息可以通过t查看，请注意：t有可能为null
//                    String msg = "错误码: " + errCode + "\n错误信息: " + errMsg;
//                    if (!TextUtils.isEmpty(errDetail)) {
//                        msg += "\n详细信息: " + errDetail;
//                    }
//                    Log.e(TAG, msg);
                Toast.makeText(LoginCodeActivity.this, "秒验失败", Toast.LENGTH_SHORT).show();
//                }
            }
        });

    }

    private void logincode(String opToken, String operator, String token) {
        EasyHttp.post(this)
                .api(new SecondTestApi().setOperator(operator).setToken(token).setOpToken(opToken)).request(new HttpCallback<VerificationCodeBean>(this) {

            @Override
            public void onSucceed(VerificationCodeBean data) {
                if (data.getCode() == 0) {
                    toast("登录成功");
                    EasyConfig.getInstance()
                            .addParam(IntentKey.TOKEN, data.getList().getToken());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.PHONE, data.getList().getUseInfo().getUserPhone());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.ACCOUNT, data.getList().getUseInfo().getUserAccount());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.TOKEN, data.getList().getToken());
                    SPUtil.put(LoginCodeActivity.this, IntentKey.INVITECODE, data.getList().getUseInfo().getInviteCode());

                    SPUtil.put(LoginCodeActivity.this, IntentKey.USERID, data.getList().getUseInfo().getUserId() + "");


                    SPUtil.put(LoginCodeActivity.this, IntentKey.USERID, String.valueOf(data.getList().getUseInfo().getUserId()));
                    bindPushRid(data.getList().getUseInfo().getUserId() + "", "miaoyan");
                    if (data.getList().isFirst()) {
                        startActivity(new Intent(LoginCodeActivity.this, InvitationCodeActivity.class).putExtra(IntentKey.USERID, data.getList().getUseInfo().getUserId() + ""));
                    }


                } else {
                    toast("验证失败");
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    /**
     * 预登录
     * <p>
     * 建议提前调用预登录接口，可以加快免密登录过程，提高用户体验
     */
    private void preVerify() {

        isPreVerifyDone = false;
        //设置在1000-10000之内
        SecVerify.setTimeOut(3000);
        //移动的debug tag 是CMCC-SDK,电信是CT_ 联通是PriorityAsyncTask
        SecVerify.setDebugMode(true);
//        SecVerify.setUseCache(true);
        SecVerify.preVerify(new PreVerifyCallback() {
            @Override
            public void onComplete(Void data) {
                // Nothing to do
//                if (devMode) {
//                    Toast.makeText(LoginCodeActivity.this, "预登录成功", Toast.LENGTH_SHORT).show();
//                }
                isPreVerifyDone = true;
            }

            @Override
            public void onFailure(VerifyException e) {
                isPreVerifyDone = true;
                // Nothing to do
                Throwable t = e.getCause();
                String errDetail = null;
                if (t != null) {
                    errDetail = t.getMessage();
                }

//                if (devMode) {
//                     登录失败
                Log.e(TAG, "preVerify failed", e);
                // 错误码
                int errCode = e.getCode();
                // 错误信息
                String errMsg = e.getMessage();
                // 更详细的网络错误信息可以通过t查看，请注意：t有可能为null
                String msg = "错误码: " + errCode + "\n错误信息: " + errMsg;
                if (!TextUtils.isEmpty(errDetail)) {
                    msg += "\n详细信息: " + errDetail;
                }
                Log.e(TAG, msg);
                Toast.makeText(LoginCodeActivity.this, "预登陆失败", Toast.LENGTH_SHORT).show();
            }
//            }
        });
    }

    private static class CustomViewClickCallback implements CustomViewClickListener {
        private int customUI;

        public CustomViewClickCallback(int customUI) {
            this.customUI = customUI;
        }

        @Override
        public void onClick(View view) {
            if (customUI == 0) {
                int id = view.getId();
                String msg = "";
                if (id == R.id.customized_btn_id_1) {
                    msg = "微信 clicked";
                    // 自定义控件点击时，SecVerify默认不关闭授权页面，若需关闭，可调用该方法
                    SecVerify.finishOAuthPage();
                    Toast.makeText(MobSDK.getContext(), msg, Toast.LENGTH_SHORT).show();
                } else if (id == R.id.customized_btn_id_3) {
//					msg = "按钮2 clicked";
                    Intent intent = new Intent(MobSDK.getContext(), LoginCodeActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    MobSDK.getContext().startActivity(intent);
                }
                // 关闭加载框
            } else if (customUI == 1) {
                // 关闭加载框
                SecVerify.finishOAuthPage();
            } else if (customUI == 4) {
                int id = view.getId();
                String msg = "";
                if (id == R.id.customized_btn_id_1) {
                    // 自定义控件点击时，SecVerify默认不关闭授权页面，若需关闭，可调用该方法
                } else if (id == R.id.customized_view_id) {
                    return;
                }
                // 关闭加载框
            }
            CommonProgressDialog.dismissProgressDialog();
        }
    }

    /**
     * 添加自定义view
     */
    private void addCustomView() {
        CustomUIRegister.addCustomizedUi(CustomizeUtils.buildCustomView(MobSDK.getContext()),
                new CustomViewClickCallback(0));

        List<View> views = new ArrayList<View>();
        TextView textView = new TextView(MobSDK.getContext());
        textView.setText("返回");
        textView.setId(R.id.customized_view_id_div);
        textView.setTextColor(0xff000000);
        textView.setTextSize(16);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//		params.addRule(RelativeLayout.RIGHT_OF, R.id.sec_verify_title_bar_left);
        params.addRule(RelativeLayout.CENTER_VERTICAL);
        params.leftMargin = ResHelper.dipToPx(LoginCodeActivity.this, 35);
        textView.setLayoutParams(params);
        views.add(textView);
        CustomUIRegister.addTitleBarCustomizedUi(views, new CustomViewClickCallback(1));
    }

    private void customizeUi() {
        SecVerify.setUiSettings(CustomizeUtils.customizeUi());
        SecVerify.setLandUiSettings(CustomizeUtils.customizeLandUi());
    }
}
